#include "BlockQueue.hpp"
#include "Task.hpp"
#include <unistd.h>
#include <time.h>

std::string opers = "+-*/%";

void *consumer(void *args)
{
    // BlockQueue<int>* bq = static_cast<BlockQueue<int>*>(args);
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    while (true)
    {
        // 消费
        // int data = bq->pop();
        Task data = bq->pop();
        // std::cout << "消费了一个数据: " << data << std::endl;

        // 计算
        // data.run();
        data();
        std::cout << "处理任务: " << data.GetTask() << " 运算结果是: " << data.GetResult() << ", thread id: " << pthread_self()<< std::endl;
        // sleep(1);
    } 
}

void *productor(void *args)
{
    int len = opers.size();
    // BlockQueue<int>* bq = static_cast<BlockQueue<int>*>(args);
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    // int data = 0;
    int x = 10;
    int y = 20;
    while (true)
    {
        // 模拟生产者生产数据
        int data1 = rand() % 10 + 1; // [1,10]
        int data2 = rand() % 10 + 1; // [1,10]
        char oper = opers[rand() % len];
        usleep(10);
        // 生产
        // data++;
        Task t(data1, data2, oper);
        // bq->push(data);
        bq->push(t);
        // std::cout << "生产了一个数据: " << data << std::endl;
        std::cout << "生产了一个任务: " << t.GetTask() << ", thread id: " << pthread_self() << std::endl;
        sleep(1);
    }
}

int main()
{
    // 因为321原则，我们的单生产单消费的代码很容易变成多生产和多消费
    srand(time(nullptr));
    // BlockQueue内部可以传递其他任务，比如任务
    // BlockQueue<int>* bq = new BlockQueue<int>();
    BlockQueue<Task> *bq = new BlockQueue<Task>();
    pthread_t c[3], p[5];
    for (int i = 0; i < 3; ++i)
    {
        pthread_create(c + i, nullptr, consumer, bq);
    }
    for (int i = 0; i < 5; ++i)
    {
        pthread_create(p + i, nullptr, productor, bq);
    }

    for (int i = 0; i < 3; ++i)
    {
        pthread_join(c[i], nullptr);
    }

    for (int i = 0; i < 5; ++i)
    {
        pthread_join(p[i], nullptr);
    }
    delete bq;
    return 0;
}
